/**
 * Bestpay.com.cn Inc.
 * Copyright (c) 2011-2018 All Rights Reserved.
 */
package com.ruoyi.SuveryInterface.SuveryUtils.util.bestPayUtils.service.V5;


import com.ruoyi.SuveryInterface.SuveryUtils.util.bestPayUtils.handler.BestpayHandler;
import com.ruoyi.SuveryInterface.SuveryUtils.util.bestPayUtils.service.BestpayServiceTemp;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import java.lang.reflect.Field;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

/**
 * @author yangbo2018
 * @version Id: BestpayServiceV3.java, v 0.1 2018/3/2 11:56 yangbo2018 Exp $$
 */
public class BestpayServiceV5 extends BestpayServiceTemp {
    public BestpayServiceV5(BestpayHandler bestpayHandler) {
        this.bestpayHandler = bestpayHandler;
    }

    private BestpayHandler bestpayHandler;

    @Override
    public BestpayHandler getBestpayHandler() {
        return bestpayHandler;
    }

    @Override
    public void setBestpayHandler(BestpayHandler bestpayHandler) {
        this.bestpayHandler = bestpayHandler;
    }

    @Override
    protected String doConvert(Object object,String platformCode,String iv) throws Exception {
        Map<String, String> signMap = new TreeMap<>();
        Field[] fields = object.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            //所有字段均需要加密
            String key = field.getName();
            String value = null;
            try {
                value = (String) field.get(object);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
                return null;
            }
            if(value!=null & !"".equals(value)) {
                signMap.put(key, value);
            }
        }
        System.out.println("第一步：生成加签原文");
        String orignSign=getOrignSign(signMap);
        System.out.println("加签原文:" + orignSign);
        //加签
        System.out.println("第二步:生成加签签文");
        String sign = bestpayHandler.sign(orignSign, BestpayHandler.SIGNATURE_ALGORITHM_SHA256);
        System.out.println("加签签文:"+sign);
        signMap.put("sign",sign);
        String encryptDataSrc = JSONObject.fromObject(signMap).toString();
        //String encryptDataSrc = JSON.toJSONString(signMap);

        System.out.println("第三步:将明文字符串和签名组装【获得：encryptDataSrc】:" + encryptDataSrc);
        //生成随机AESKey
        String aesKey = "W5tIO7xhBXWBZpLM";//RandomStringUtils.randomAlphanumeric(16);
        System.out.println("第四步 -> 生成随机aesKey，用于AES加密，aesKey=" + aesKey);
        //加密生成业务参数原文
        String encryptData=bestpayHandler.encode(aesKey,encryptDataSrc,iv);
        System.out.println("第五步：使用aesKey对报文数据（encryptDataSrc）进行AES加密【获得:encryptData】:" + encryptData);

        //加密AESKey
        String encryptKey = bestpayHandler.rsaEncode(aesKey);
        System.out.println("第六步 -> 利用账公钥，将aesKey进行RSA加密【获得:encryptKey】:" + encryptKey);

        //最终请求参数
        Map<String, String> request = new TreeMap<>();
        request.put("merchantNo",platformCode);
        request.put("encryptKey", encryptKey);
        request.put("encryptData", encryptData);
        //String requestStr = JSON.toJSONString(request);
        String requestStr = JSONObject.fromObject(request).toString();
        System.out.println("第七步：得到最终请求参数:" + requestStr);
        return requestStr;
    }

    @Override
    protected boolean doVerify(String response) {
        JsonConfig config = new JsonConfig();
        config.setIgnoreDefaultExcludes(true);
        JSONObject jsonObject = JSONObject.fromObject(response, config);
        Iterator<String> sIterator = jsonObject.keys();
        StringBuffer sb=new StringBuffer();
        String sign=null;
        while(sIterator.hasNext()) {
            String key=sIterator.next();
            Object value=jsonObject.get(key);
            if("sign".equals(key)){
                sign=(String)value;
            }else{
                sb.append("&").append(key).append("=").append(value);

            }

        }
        String tobeVerify=sb.substring(1);
        System.out.println("待验签tobeVerify："+tobeVerify);

        try {
            return bestpayHandler.verify(tobeVerify,sign, BestpayHandler.SIGNATURE_ALGORITHM_SHA256);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }

    private String getOrignSign(Map<String,String> jsonMap){
        StringBuilder sb = new StringBuilder();
        for (Map.Entry entry : jsonMap.entrySet()) {
            sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
        }
        if (sb.length() > 1) {
            sb.deleteCharAt(sb.length() - 1);
        }
        return sb.toString();
    }
}
